<?php
	require_once 'SQLHelper.class.php';
	class UserService{
		public function addUser($username, $passwd, $email){
			$sqlHelper = new SQLHelper();
			$sql = "insert into user (username,passwd,email,lastLogin,isLogin) values('$username',md5('$passwd'),'$email',now(),0 )";
			return $sqlHelper->exc_dml($sql);
		}
		
		public function getUserByName($username){
			$sqlHelper = new SQLHelper();
			$sql = "select * from user where username='$username'";
			$arr = $sqlHelper->exc_dql2_first($sql);
			$sqlHelper->connect_close();
			//file_put_contents("d:/mylog.log",$arr['passwd']."\r\n",FILE_APPEND);
			return $arr;
		}
		
		public function getUserList($username){
			$sqlHelper = new SQLHelper();
			$sql = "select username from user where username != '$username'";
			$arrUserlist = $sqlHelper->exc_dql2($sql);
			//file_put_contents("d:/mylog.log",'getUserList is end'."\r\n",FILE_APPEND);
			$arrUnreadMsg = $this->getUnreadMsg($username);
			//file_put_contents("d:/mylog.log",'getReadMeg is end'."\r\n",FILE_APPEND);
			$sqlHelper->connect_close();
			$arr = array("userlist" => $arrUserlist, "unreadmsg" => $arrUnreadMsg);
			//file_put_contents("d:/mylog.log",count($arr['userlist']).'isIN'."\r\n",FILE_APPEND);
			//返回消息格式
			/*
			$res_info = "[";
			for($i=0; $i<count($arr); $i++){
				$row = $arr[$i];
				if($i == (count($arr)-1)){
					$res_info.='{"username":"'.$row['username'].'"}]';
				}else{
					$res_info.='{"username":"'.$row['username'].'"},';
				}
			}
			*/
			$res_info = json_encode($arr);
			//file_put_contents("d:/mylog.log",$res_info."\r\n",FILE_APPEND);
			return $res_info;
		}

		public function getUnreadMsg($username){
			$sqlHelper = new SQLHelper();
			$sql = "select m.sender, count(m.sender) count from user u, messages m where u.username = m.getter and u.username='$username' and m.isGet=0 group by m.sender";
			$arr = $sqlHelper->exc_dql2($sql);
			$sqlHelper->connect_close();
			return $arr;
		}
		
		public function userLogin($username){
			$sqlHelper = new SQLHelper();
			$sql = "update user set isLogin=1 where username='$username'";
			return $sqlHelper->exc_dml($sql);
		}
		
		public function userLogout($username){
			$sqlHelper = new SQLHelper();
			$sql = "update user set isLogin=0 where username='$username'";
			return $sqlHelper->exc_dml($sql);
		}
		
	}